package com.bidevalution.business.impl;

import com.bidevalution.business.service.BeSectionParamsService;
import com.bidevalution.business.service.BeSectionParticipantService;
import com.bidevalution.business.service.SmsSendService;
import com.bidevalution.dao.entity.BeSectionParticipant;
import com.bidevalution.dao.entity.SmsSendFail;
import com.bidevalution.dao.mapper.SmsSendFailMapper;
import com.bidevalution.support.context.Constants;
import com.bidevalution.support.context.SectionStateEnum;
import com.bidevalution.support.context.SmsTemplateCode;
import com.google.common.collect.Maps;
import com.qtp.core.common.RemoteService;
import com.qtp.core.util.DateUtil;
import com.qtp.core.util.GsonUtil;
import com.qtp.core.util.IdsUtil;
import com.qtp.core.util.OConvertUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.util.List;
import java.util.Map;

/**
 * 短信发送实现类
 * @author shenh@glodon.com
 * @date 2019-07-08 10:46
 */
@Service(value = "smsSendService")
@Transactional(rollbackFor = Exception.class)
public class SmsSendServiceImpl implements SmsSendService {

    @Autowired
    private BeSectionParamsService beSectionParamsService;
    @Autowired
    private SmsSendFailMapper smsSendFailMapper;
    @Autowired
    private BeSectionParticipantService beSectionParticipantService;
    private Logger log = Logger.getLogger(getClass());
    /**
     * 发送短信
     *
     * @param code  模板编号
     * @param phone 电话号码, 多个以逗号分隔
     * @param data  替换内容,Json字符串
     */
    @Override
    public boolean sendMsg(String code, String phone, String data) {
        try {
            if (StringUtils.isBlank(code)) {
                log.error("短信发送失败：模板编号不能为空！");
                return false;
            }
            if (StringUtils.isBlank(phone)) {
                log.error("短信发送失败：电话号码不能为空！");
                return false;
            }
            //拼接参数
            Map<String, Object> params = Maps.newHashMap();
            params.put("code", code);
            params.put("phone", phone);
            params.put("data", data);
            params.put("smsTempType", Constants.ONE);
            System.out.println(data);
            log.debug(MessageFormat.format("发送短信,参数为：{}", GsonUtil.toJsonWithGson(params)));

            //获得发送短信url
            String url = beSectionParamsService.getOneSysParamValue("sms_send_url");
            if (StringUtils.isBlank(url)) {
                SmsSendFail smsSendFail = new SmsSendFail();
                smsSendFail.setSeqId(IdsUtil.uuid());
                smsSendFail.setContent(GsonUtil.toJsonWithGson(params));
                smsSendFail.setFailReason("短信发送失败：未找到短信平台地址，请在参数管理中进行配置！");
                smsSendFail.setPhone(phone);
                smsSendFailMapper.insert(smsSendFail);
                return false;
            }
            log.debug(MessageFormat.format("短信平台发送地址为：{}", url));


            //连接开始推送
            String response = RemoteService.getRemoteInfo(url, params);
            log.debug(MessageFormat.format("短信平台返回信息内容为：{}", response));
            if(StringUtils.isBlank(response)){
                SmsSendFail smsSendFail = new SmsSendFail();
                smsSendFail.setSeqId(IdsUtil.uuid());
                smsSendFail.setContent(GsonUtil.toJsonWithGson(params));
                smsSendFail.setFailReason("短信发送失败：短信平台连接失败!");
                smsSendFail.setPhone(phone);
                smsSendFailMapper.insert(smsSendFail);
                return false;
            }
            Map<String, Object> resultMap = GsonUtil.jsonToMapWithGson(response);
            if (resultMap == null || resultMap.size() == 0) {
                log.error("短信发送失败：短信平台返回结果为空!");
                SmsSendFail smsSendFail = new SmsSendFail();
                smsSendFail.setSeqId(IdsUtil.uuid());
                smsSendFail.setContent(GsonUtil.toJsonWithGson(params));
                smsSendFail.setFailReason("短信发送失败：短信平台返回结果为空!");
                smsSendFail.setPhone(phone);
                smsSendFailMapper.insert(smsSendFail);
                return false;
            } else if (Constants.CON_FALSE.equals(OConvertUtils.getString(resultMap.get("success")))) {
                log.error("短信发送失败：" + OConvertUtils.getString(resultMap.get("error")));
                SmsSendFail smsSendFail = new SmsSendFail();
                smsSendFail.setSeqId(IdsUtil.uuid());
                smsSendFail.setContent(GsonUtil.toJsonWithGson(params));
                smsSendFail.setFailReason(OConvertUtils.getString(resultMap.get("error")));
                smsSendFail.setPhone(phone);
                smsSendFailMapper.insert(smsSendFail);
                return false;
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
        return true;
    }

    /**
     * 获取招标代理手机号
     * @param sectionId
     */
    @Override
    public String getAgentPhones(String sectionId) {
        //TODO 需要从平台接口中获取手机号,目前先写死
        return "15111111111";
    }

    /**
     * 获取投标单位手机号
     * @param sectionId
     */
    @Override
    public String getBidPhones(String sectionId) {
        //TODO 需要从平台接口中获取手机号,多个用逗号分隔，目前先写死
        return "15222222222";
    }

    /**
     * 发送流程短信
     * @param sectionId
     * @param sectionStage
     */
    @Override
    public void sendBidFlowMsg(String sectionId, String sectionStage) throws Exception {
        //获取投标人手机号
        String phones = getBidPhones(sectionId);
        Map<String, Object> paramMap = Maps.newHashMap();
        if(SectionStateEnum.decrypting.getValue().equals(sectionStage)) {
            //进入解密阶段
            sendMsg(SmsTemplateCode.kb0005.getValue(), phones,  GsonUtil.toJsonWithGson(paramMap));
        } else if(SectionStateEnum.paramdrawing.getValue().equals(sectionStage)) {
            //进入参数抽取
            sendMsg(SmsTemplateCode.kb0010.getValue(), phones,  GsonUtil.toJsonWithGson(paramMap));
        } else if(SectionStateEnum.reviewing.getValue().equals(sectionStage)) {
            //进入评审
            sendMsg(SmsTemplateCode.kb0011.getValue(), phones,  GsonUtil.toJsonWithGson(paramMap));
        } else if(SectionStateEnum.finished.getValue().equals(sectionStage)) {
            List<BeSectionParticipant> beSectionParticipants = beSectionParticipantService.getCandidateList(sectionId);
            if(beSectionParticipants != null && beSectionParticipants.size() > 0){
                StringBuilder candidates = new StringBuilder();
                for(int i=0; i<beSectionParticipants.size(); i++){
                    candidates.append("第").append(i+1).append("中标候选人为【").append(beSectionParticipants.get(i).getParticipantName()).append("】");
                }
                paramMap.put("candidates", candidates);
                //代理和投标人都需要发送短信
                phones = getAgentPhones(sectionId) + Constants.COMMA + phones;
                //进入结束页面
                sendMsg(SmsTemplateCode.kb0012.getValue(), phones, GsonUtil.toJsonWithGson(paramMap));
            }
        }
    }

}
